import Seo from '@/core/components/Seo'
import LogoSpinner from '@/core/components/elements/Spinner/LogoSpinner'
import { getIdFromSlug } from '@/core/utils/slug'
import PageNotFound from '@/pages/404'
import dynamic from 'next/dynamic'
import { useRouter } from 'next/router'
import cookie from 'cookie'
import variantApi from '@/lib/product/api/variantApi'
import { useProductContext } from '@/contexts/ProductContext'
import { useEffect } from 'react'

const BasicLayout = dynamic(() => import('@/core/components/layouts/BasicLayout'))
const Product = dynamic(() => import('@/lib/product/components/Product/Product'))

export async function getServerSideProps(context) {
  const { slug } = context.query
  const cookies = context.req.headers.cookie
  const cookieObj = cookies ? cookie.parse(cookies) : {}
  const auth = cookieObj.auth ? JSON.parse(cookieObj.auth) : {}
  const authToken = auth?.token || ''

  let product = await variantApi({ id: getIdFromSlug(slug), headers: { Token: authToken } })
  if (product?.length == 1) {
    product = product[0]
   /* const regexHtmlTags = /(<([^>]+)>)/gi
    const regexHtmlTagsExceptP = /<\/?(?!p\b)[^>]*>/g
    product.description = product.description
      .replace(regexHtmlTagsExceptP, ' ')
      .replace(regexHtmlTags, ' ')
      .trim()*/
  } else {
    product = null
  }

  return {
    props: { product }
  }
}

export default function ProductDetail({ product }) {
  const router = useRouter()

  const { setProduct } = useProductContext()

  useEffect(() => {
    if (product) {
      setProduct(product)
    }
  }, [product, setProduct])

  if (!product) return <PageNotFound />

  return (
    <BasicLayout>
      <Seo
        title={product?.name || '' + ' - Indoteknik.com' || ''}
        description='Temukan pilihan produk B2B Industri &amp; Alat Teknik untuk Perusahaan, UMKM &amp; Pemerintah dengan lengkap, mudah dan transparan.'
        openGraph={{
          url: process.env.NEXT_PUBLIC_SELF_HOST + router.asPath,
          images: [
            {
              url: product?.image,
              width: 800,
              height: 800,
              alt: product?.name
            }
          ],
          type: 'product'
        }}
        additionalMetaTags={[
          {
            name: 'keywords',
            content: `${product?.name}, Harga ${product?.name}, Beli ${product?.name}, Spesifikasi ${product?.name}`
          }
        ]}
      />
      {!product && (
        <div className='container mx-auto flex justify-center pt-10'>
          <LogoSpinner width={36} height={36} />
        </div>
      )}
      {product && <Product product={product} isVariant={true} />}
    </BasicLayout>
  )
}
